package com.sencorsta.ids.core.data.mysql;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Properties;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.sencorsta.ids.core.log.Out;

/**
 * 要实现单例模式，保证全局只有一个数据库连接池
 *
 * @author ICe
 * <p>
 * 2016年10月21日
 */
public class DBPoolConnection {
    private static volatile DBPoolConnection dbPoolConnection = null;
    private static DruidDataSource druidDataSource = null;

    /*
    *   driverClassName=com.mysql.jdbc.Driver
        url=jdbc:mysql://127.0.0.1:3306/DruidTest
        username=root
        password=0000
        filters=stat
        initialSize=2
        maxActive=300
        maxWait=60000
        timeBetweenEvictionRunsMillis=60000
        minEvictableIdleTimeMillis=300000
        validationQuery=SELECT 1
        testWhileIdle=true
        testOnBorrow=false
        testOnReturn=false
        poolPreparedStatements=false
        maxPoolPreparedStatementPerConnectionSize=200
    *
    * */

//    static {
//        HashMap<String,String> properties=new HashMap<>();
//        properties.put("driverClassName","com.mysql.cj.jdbc.Driver");
//        properties.put("url","jdbc:mysql://192.168.0.188:3306/test");
//        properties.put("username","root");
//        properties.put("password","1qaz@WSX123");
//        properties.put("filters","stat");
//        properties.put("initialSize","2");
//        properties.put("maxActive","30");
//        properties.put("maxWait","60000");
//        properties.put("timeBetweenEvictionRunsMillis","60000");
//        properties.put("minEvictableIdleTimeMillis","300000");
//        properties.put("validationQuery","SELECT 1");
//        properties.put("testWhileIdle","false");
//        properties.put("testOnBorrow","false");
//        properties.put("testOnReturn","false");
//        properties.put("poolPreparedStatements","false");
//        properties.put("maxPoolPreparedStatementPerConnectionSize","200");
//
//
//        //Properties properties = loadPropertiesFile("db_server.properties");
//        try {
//            //druidDataSource = (DruidDataSource)DruidDataSourceFactory.createDataSource(properties);    //DruidDataSrouce工厂模式
//
//            druidDataSource = (DruidDataSource)DruidDataSourceFactory.createDataSource(properties);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 数据库连接池单例
     *
     * @return
     */
    public static DBPoolConnection getInstance() {
        if (null == dbPoolConnection) {
            synchronized (DBPoolConnection.class) {
                if (null == dbPoolConnection) {
                    dbPoolConnection = new DBPoolConnection();
                }
            }
        }
        return dbPoolConnection;
    }

    public void init(HashMap<String, String> properties) throws Exception {
        properties.put("driverClassName", "com.mysql.cj.jdbc.Driver");
        //properties.put("url","jdbc:mysql://192.168.0.188:3306/test");
        //properties.put("username","root");
        //properties.put("password","1qaz@WSX123");
        properties.put("filters", "stat");
        properties.put("initialSize", "2");
        properties.put("minIdle", "5");
        properties.put("maxActive", Runtime.getRuntime().availableProcessors()*2+1+"");
        properties.put("maxWait", "15000");

//        properties.put("maxActive", 1000+"");

        properties.put("timeBetweenEvictionRunsMillis", "2000");

        properties.put("minEvictableIdleTimeMillis", "600000");
        properties.put("minEvictableIdleTimeMillis", "900000");

        properties.put("validationQuery", "SELECT 1");
        properties.put("testWhileIdle", "false");
        properties.put("testOnBorrow", "false");
        properties.put("testOnReturn", "false");
        properties.put("poolPreparedStatements", "false");
//        properties.put("maxPoolPreparedStatementPerConnectionSize", "20");
        properties.put("asyncInit", "true");
        druidDataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);

        if (new DBDao().test()) {
            Out.info("Database服务初始化成功！", " --> ", properties.get("url"));
        } else {
            throw new Exception("Database服务初始化失败");
        }
    }

    /**
     * 返回druid数据库连接
     *
     * @return
     * @throws SQLException
     */
    public DruidPooledConnection getConnection() throws SQLException {
        return druidDataSource.getConnection();
    }

    /**
     * @param fullFile 配置文件名
     * @return Properties对象
     */
    private static Properties loadPropertiesFile(String fullFile) {
        String webRootPath = null;
        if (null == fullFile || fullFile.equals("")) {
            throw new IllegalArgumentException("Properties file path can not be null" + fullFile);
        }
        webRootPath = DBPoolConnection.class.getClassLoader().getResource("").getPath();
        webRootPath = new File(webRootPath).getParent();
        InputStream inputStream = null;
        Properties p = null;
        try {
            inputStream = new FileInputStream(new File(webRootPath + File.separator + fullFile));
            p = new Properties();
            p.load(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return p;
    }

}